package servlet;

import model.Department;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet("/addPart.action")
public class addPartServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        Department part=new Department();

        try {
            BeanUtils.populate(part,req.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd  HH:mm");
        //创建日期值
        Date now=new Date();
        String format = dateFormat.format(now);
        //格式化日期
        part.setUpdateTime(format);
//
        File file = new File("C:\\Users\\FeiFei\\Desktop\\test.txt");

        List<Department> partList;
        // 从流读取对象信息
        if (file.exists() && file.length() > 0) {
            try (FileInputStream fis = new FileInputStream(file);
                 ObjectInputStream ois = new ObjectInputStream(fis)) {
                partList = (List<Department>) ois.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                partList = new ArrayList<>();
            }
        } else {
            partList = new ArrayList<>();
        }

        partList.add(part);
        try (FileOutputStream fos = new FileOutputStream(file);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(partList);
            oos.close();
            fos.close();
        }
        System.out.println(partList);
        resp.sendRedirect(req.getContextPath()+"/partInfo.jsp");
    }
}
